//时间格式化函数
function formDate(date) {
    //日期不能截取字符串,因为存储的是0时区,和北京时间相差8小时 2021-09-16T09:19:00.000Z
    let myDate = new Date(date)
    // console.log(myDate);//Thu Sep 16 2021 17:19:00 GMT+0800 (中国标准时间)
    return `${myDate.getFullYear()}-${myDate.getMonth() + 1}-${myDate.getDate()}`
}
//因为首页,列表页,详情页都有随推荐,最新评论,分类导航,搜索

//获取随机推荐
$.get('/posts/random', function (response) {
    let str = `
    {{each data}}
    <li>
        <a href="../detail.html?id={{$value._id}}">
            <p class="title">{{$value.title}}</p>
            <p class="reading">阅读({{$value.meta.views}})</p>
            <div class="pic">
                <img src="{{$value.thumbnail}}" alt="">
            </div>
        </a>
    </li>
    {{/each}}
    `
    let html = template.render(str, { data: response })
    $('.random').html(html)
})

//最新评论
$.get('/comments/lasted', function (response) {
    let str = `
    {{each data}}
    <li>
        <!--点击跳转到具体文章,查看评论-->
        <a href="../detail.html?id={{$value.post}}">
            <div class="avatar">
                <img src="{{$value.author.avatar}}" alt="">
            </div>
            <div class="txt">
                <p>
                    <span>{{$value.author.nickName}}</span>{{$imports.formDate($value.createAt)}}说:
                </p>
                <p>{{$value.content}}</p>
            </div>
        </a>
    </li>
    {{/each}}
    `
    let html = template.render(str, { data: response })
    $('.discuz').html(html)
})

//分类导航
$.get('/categories', function (response) {
    let str = `
    {{each data}}
    <li>
        <a href="../list.html?id={{$value._id}}&title={{$value.title}}">
            <i class="fa {{$value.className}}"></i>{{$value.title}}
        </a>
    </li>
    {{/each}}
    `
    let html = template.render(str, { data: response })
    $('.topnav ul').html(html)
    $('.nav').html(html)
})

//文章搜索
$('.search form').on('submit', function () {
    let key = $(this).children('.keys').val()
    //console.log(key)

    //搜索,并展示数据,放到search.html中
    //跳转到搜索页,并且带上关键字
    location.href = 'search.html?key=' + key

    return false
})

function getUrlParams(name) {
    //先去掉?号
    let paramsArray = location.search.substr(1).split("&")
    for (let string of paramsArray) {
        //再通过=号拆分
        let tmp = string.split("=")
        //tmp[0]:键   tmp[1]:值
        if (tmp[0] === name) {
            return tmp[1]
        }
    }
    return -1  //代表没有name键对应的值
}
